﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SaiLing.Cache;
using SaiLing.Common;
using SaiLing.Domain.Specification;
using SaiLing.Exceptions;
using SaiLing.SingleSignOn.Application.Core.DataTransferObject.System;
using SaiLing.SingleSignOn.Application.Service;
using SaiLing.SingleSignOn.Application.Service.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Entities.DataTransferObject;
using SaiLing.Web;

namespace SaiLing.SingleSignOn.WebApi.Controllers
{
    public class LoginController : Controller
    {
        private IAccountService AccountService { get; set; }

        private ICacheService CacheService { get; set; }

        public LoginController(IAccountService accountService, ICacheService cacheService)
        {
            this.AccountService = accountService;
            this.CacheService = cacheService;
        }
        public IActionResult Index()
        {
            //var user = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme).Result;
            //ViewBag.RedirectUrl = redirectUrl;
            //ViewBag.Appkey = appkey;
            return View();
        }

        [HttpPost]
        public async Task<ApiJsonResultData> Index(AccountLoginModel model, string redirectUrl, string appkey)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                //var app = await ServiceFactory.GetService<IApplicationService>().GetByCondition(new DirectSpecification<Domain.Entities.System.Application>(x => x.AppKey == model.AppKey));
                //if (app == null)
                //    return new BadRequestResult();
                var user = await AccountService.SignIn(model.UserName, model.Password);
                var siginUser = new SiginUser() { LoginName = user.LoginName, Name = user.Name, SiginIp = Web.HttpContext.GetIpAddress(), SiginTime = DateTime.Now };
                var token = Guid.NewGuid().ToString().ToLower().Replace("-", "");
                var claims = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("token", token), new Claim("user", JsonConvert.SerializeObject(siginUser)) }, CookieAuthenticationDefaults.AuthenticationScheme));
                await CacheService.AddAsync(token, siginUser);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claims, new AuthenticationProperties
                {
                    IsPersistent = true,
                    //RedirectUri = app.Url,
                    ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(180)),
                });
                if (string.IsNullOrEmpty(redirectUrl))
                    redirectUrl = "/";
                x.RedirectUrl = redirectUrl.AddQueryParam("token", token);
            });
        }
    }
}